# ~*~ coding: utf-8 ~*~
import os
import json

from apps.common.utils import gen_datetime_path

from apps.config import ConfigManager

CONFIG = ConfigManager.load_user_config()


def get_recorder(session):
    return Recorder(session)


class Recorder(object):
    def __init__(self, session):
        self.session = session
        self.record_path = self.__class__.get_record_file(self.session.sid)
        self.f = None

    @staticmethod
    def get_record_file(session_id):
        record_full_path = os.path.join(CONFIG.RECORDS_LOG_DIR, gen_datetime_path())
        if not os.path.exists(record_full_path):
            os.makedirs(record_full_path, exist_ok=True)

        record_path = os.path.join(gen_datetime_path(), '{}.cast'.format(session_id))
        return record_path

    @property
    def header(self):
        return {
            "version": 2,
            "width": self.session.client.request.meta.get('width'),
            "height": self.session.client.request.meta.get('height'),
            "timestamp": round(self.session.date_start),
            "title": self.session.sid,
            "env": {
                "TERM": os.environ.get('TERM'),
                "SHELL": os.environ.get('SHELL', '/bin/bash')
            },
        }

    def record(self, data):
        self.f.write(json.dumps(data) + '\n')

    def start(self, data=None):
        file_path = os.path.join(CONFIG.RECORDS_LOG_DIR, self.record_path)
        self.f = open(file_path, 'a')
        self.record(self.header)
        if data:
            self.record(data)

    def stop(self, data=None):
        if data:
            self.record(data)
        self.f.flush()
        self.f.close()
